package alipay.openplatform.edu.campus.jiuye.api.controller.topic;

import alipay.openplatform.edu.campus.jiuye.api.utils.ContextUtils;
import alipay.openplatform.edu.campus.jiuye.common.cache.CacheManagerService;
import alipay.openplatform.edu.campus.jiuye.common.enums.ResultCode;
import alipay.openplatform.edu.campus.jiuye.common.exception.OnlineRuntimeException;
import alipay.openplatform.edu.campus.jiuye.common.page.Page;
import alipay.openplatform.edu.campus.jiuye.common.page.PageUtil;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.model.vo.TopicInfoVO;
import alipay.openplatform.edu.campus.jiuye.model.vo.UserBaseInfo;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import alipay.openplatform.edu.campus.jiuye.service.iservice.topic.ITopicInfoService;
import alipay.openplatform.edu.campus.jiuye.service.iservice.user.IUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 主题信息接口
 */
@Controller
public class TopicInfoController {
    private final static Logger log = LoggerFactory.getLogger(TopicInfoController.class);
    @Autowired
    private ITopicInfoService iTopicInfoService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private CacheManagerService cacheManagerService;

    /**
     * 根据主题名称和状态查询(模糊查询)
     * url:/jiuye/api/getTopicInfoByStatusAndName
     * sj 2016 10 14 require : 按照类型分类(全部 ''、校园宣讲 1、本市招聘 0、公务员 2)。按照是否置顶查询(0置顶 1未置顶)
     * @param topicTitle
     * @param timeState
     * @param topicType
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jiuye/api/getTopicInfoByStatusAndName", method = RequestMethod.POST)
    public ApiResult getTopicInfoByStatusAndName(@RequestParam(value = "topicTitle", required = false) String topicTitle,
                                                 @RequestParam(value = "timeState", required = false) String timeState,
                                                 @RequestParam(value = "topicType", required = false) String topicType,
                                                 @RequestParam(value = "schoolName", required = false) String schoolName,
                                                 @RequestParam(value = "startTime", required = false) String startTime,
                                                 @RequestParam(value = "endTime", required = false) String endTime,
                                                 @RequestParam(value = "pageNo", required = false) String pageNo,
                                                 @RequestParam(value = "pageSize", required = false) String pageSize) {
        log.info("查看主题信息[TopicInfoController][getTopicInfoByStatusAndName]param{topicType :" + topicTitle + " timeState :" + timeState + ","+"topicType :"+topicType+","+ "pageNo :" + pageNo + "," + "pageSize :" + pageSize + "}");

        String userId = ContextUtils.getUserId(request);
//        String userId = "2088302167243547";
        if (userId == null) {
            return ApiResult.buildSuccess(ResultCode.AUTH_UNAUTHORIZED.getCode(), ResultCode.AUTH_UNAUTHORIZED.getName(), null);
        }
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("topicTitle", topicTitle);
        paramter.put("timeState", timeState);
        paramter.put("topicType", topicType);
        paramter.put("schoolName",schoolName);
        paramter.put("startTime",startTime);
        paramter.put("endTime",endTime);
        Page p = PageUtil.buidPagebean(request, paramter);
        try {
            p = iTopicInfoService.selectTopicInfoPOByTitleAndStatus(p);
        } catch (Exception e) {
            log.error("[查看主题信息异常][TopicInfoController]{getTopicInfoByStatusAndName()}", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        ApiResult apiResult = ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), p);
        return apiResult;
    }

    /**
     * 结束主题发布
     * url:/jiuye/api/stopPublish
     *
     * @param topicId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jiuye/api/stopPublish", method = RequestMethod.POST)
    public ApiResult stopPublish(@RequestParam(value = "topicId", required = true) String topicId) {
        log.info("结束发布[TopicInfoController][stopPublish]param{topicId:" + topicId + "}");
        String userId = ContextUtils.getUserId(request);
//        String userId = "2088302167243547";
        if (userId == null) {
            return ApiResult.buildSuccess(ResultCode.AUTH_UNAUTHORIZED.getCode(), ResultCode.AUTH_UNAUTHORIZED.getName(), null);
        }
        try {
            iTopicInfoService.updateTopicState(Integer.parseInt(topicId));
        } catch (Exception e) {
            log.error("[结束发布主题异常][TopicInfoController]{stopPublish()}", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }

        ApiResult apiResult = ApiResult.build(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName());
        return apiResult;
    }

    /**
     * 查看主题详情
     * url:/jiuye/api/getTopicInfoDetail
     *
     * @param topicId
     * @return
     */
    public ApiResult getTopicInfoDetail(String topicId) {
        return null;
    }

    /**
     * 根据城市id查询对应专题
     *
     * @param pageNo   当前页号
     * @param pageSize 分页大小
     * @return
     */
    @RequestMapping("/jiuye/api/getTopicInfoByLocation")
    @ResponseBody
    public ApiResult getTopicInfoByLocation(String pageNo, String pageSize) {
        UserBaseInfo userBaseInfo = getUserInfo();
        if (userBaseInfo == null) {
            return ApiResult.buildSuccess(ResultCode.AUTH_UNAUTHORIZED.getCode(), ResultCode.AUTH_UNAUTHORIZED.getName(), null);
        }
        Map<String, Object> paramter = new HashMap<String, Object>();
        String cityId = userBaseInfo.getCityId();
        paramter.put("cityId", cityId);
        Page p = PageUtil.buidPagebean(request, paramter);
        log.info("TopicInfoController|getTopicInfoList|params:cityId={},pageNo={},pageSize={}", cityId, pageNo, pageSize);
        try {
            p = iTopicInfoService.getTopicInfoByLocation(p);
            return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), p);
        } catch (Exception e) {
            log.error("TopicInfoController|getTopicInfoByLocation|params:e={}", e);
        }
        return null;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    private UserBaseInfo getUserInfo() {
        String userId = ContextUtils.getUserId(request);
        //String userId = "2088302167243547";

        UserBaseInfo userBaseInfo = null;
        try {
            userBaseInfo = iUserInfoService.getUserInfoByUserId(userId);
        } catch (InvocationTargetException e) {
            log.error("TopicInfoController|getTopicInfoList|params:e={}", e);
        } catch (IllegalAccessException e) {
            log.error("TopicInfoController|getTopicInfoList|params:e={}", e);
        }
        return userBaseInfo;
    }

    /**
     * 根据城市id和专题类别查询
     *
     * @param topicType 类型0 招聘会 1 校园专题 2公务员  cityId 城市id
     * @param pageNo    当前页号
     * @param pageSize  分页大小
     * @return
     */
    @RequestMapping("/jiuye/api/getTopicInfoList")
    @ResponseBody
    public ApiResult getTopicInfoList(@RequestParam(value = "topicType", required = true) String topicType, String pageNo, String pageSize) {
        UserBaseInfo userBaseInfo = getUserInfo();
        if (userBaseInfo == null) {
            return ApiResult.buildSuccess(ResultCode.AUTH_UNAUTHORIZED.getCode(), ResultCode.AUTH_UNAUTHORIZED.getName(), null);
        }
        Map<String, Object> paramter = new HashMap<String, Object>();
        String cityId = userBaseInfo.getCityId();
        String schoolId = userBaseInfo.getSchoolId();
        paramter.put("cityId", cityId);
        paramter.put("schoolId", schoolId);
        paramter.put("topicType", topicType);
        Page p = PageUtil.buidPagebean(request, paramter);
        log.info("TopicInfoController|getTopicInfoList|params:cityId={},topicType={},pageNo={},pageSize={}", cityId, topicType, pageNo, pageSize);
        try {
            p = iTopicInfoService.getTopicInfoList(p);
            return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), p);
        } catch (Exception e) {
            log.error("TopicInfoController|getTopicInfoList|params:e={}", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());

        }
    }

    /**
     * 根据城市名称 学校名称 专题名称搜索
     *
     * @param condition 搜索条件
     * @param pageNo    当前页号
     * @param pageSize  分页大小
     * @return
     */
    @RequestMapping("/jiuye/api/searchTopic")
    @ResponseBody
    public ApiResult searchTopic(@RequestParam(value = "condition", required = true) String condition, String pageNo, String pageSize) {
        log.info("TopicInfoController|searchTopic|params:condition={},pageNo={},pageSize={}", condition, pageNo, pageSize);
        Map<String, Object> paramter = new HashMap<String, Object>();
        paramter.put("condition", condition);
        Page p = PageUtil.buidPagebean(request, paramter);
        try {
            p = iTopicInfoService.searchTopic(p);
            return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), p);
        } catch (Exception e) {
            log.error("TopicInfoController|searchTopic|params:e={}", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
    }

    /**
     * 添加主题
     *
     * @param topicInfoVO 传入参数对象
     * @return
     */
    @ResponseBody
    @RequestMapping("/jiuye/api/addTopic")
    public ApiResult addTopic(@RequestBody TopicInfoVO topicInfoVO) {
        log.info("添加主题|TopicInfoController|addTopic|params:topicInfoVO={}", topicInfoVO);
        if (ObjectUtils.isEmpty(topicInfoVO)) {
            throw new OnlineRuntimeException("PARAM_ERROR", "接受对象为空值!");
        }
        if (ObjectUtils.isNull(topicInfoVO.getTopicTitle()) || topicInfoVO.getTopicTitle().length() > 50) {
            log.error("添加主题错误:标题过长或标题为空|TopicInfoController|updateTopic|",topicInfoVO.getTopicTitle());
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        if (ObjectUtils.isNull(topicInfoVO.getPlace()) && topicInfoVO.getPlace().length() > 100) {
            log.error("添加主题错误:地址过长或地址为空|TopicInfoController|updateTopic|",topicInfoVO.getPlace());
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }

        try {
            String userId = ContextUtils.getUserId(request);
            int createmanId = Integer.valueOf(userId);
            iTopicInfoService.addTopic(createmanId, topicInfoVO);
        } catch (Exception e) {
            log.error("添加主題异常|TopicInfoController|addTopic", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }

        ApiResult apiResult = ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), null);
        return apiResult;
    }

    /**
     * 修改主题
     *
     * @param topicInfoVO 传入参数对象
     * @return
     */
    @ResponseBody
    @RequestMapping("/jiuye/api/updateTopic")
    public ApiResult updateTopic(@RequestBody TopicInfoVO topicInfoVO) {
        log.info("编辑主题|TopicInfoController|updateTopic|params:topicInfoVO={}", topicInfoVO);
        if (ObjectUtils.isEmpty(topicInfoVO)) {
            throw new OnlineRuntimeException("PARAM_ERROR", "接受对象为空值!");
        }
        if (ObjectUtils.isNull(topicInfoVO.getTopicTitle()) || topicInfoVO.getTopicTitle().length() > 50) {
            log.error("编辑主题错误:标题过长或标题为空|TopicInfoController|addTopic|",topicInfoVO.getTopicTitle());
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        if (ObjectUtils.isNull(topicInfoVO.getPlace()) && topicInfoVO.getPlace().length() > 100) {
            log.error("编辑主题错误:地址过长或地址为空|TopicInfoController|addTopic|",topicInfoVO.getPlace());
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        try {
            iTopicInfoService.updateTopic(topicInfoVO);
        } catch (Exception e) {
            log.error("修改主題异常|TopicInfoController|updateTopic", e);
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), null);
    }

    @ResponseBody
    @RequestMapping("/jiuye/api/removeTopic")
    public ApiResult removeTopic(@RequestParam(value = "topicId", required = true) Integer topicId) {
        log.info("删除主题|TopicInfoController|removeTopic|params:topicId={}", topicId);
        Integer changeNo = null;
        try {
            changeNo = iTopicInfoService.removeTopicByTopicIdAndIfDel(topicId);
        } catch (Exception e) {
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName() + e);
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), changeNo == 1);
    }

    @ResponseBody
    @RequestMapping("/jiuye/api/clearCache")
    public ApiResult clearCache(@RequestParam(value = "key", required = true) String key) {
        try {
            cacheManagerService.del(key);
        } catch (Exception e) {
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName() + e);
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), true);
    }

    @ResponseBody
    @RequestMapping("/jiuye/api/topTopic")
    public ApiResult topTopic(@RequestParam(value = "topicId",required = true) Integer topicId,
                              @RequestParam(value = "topState",required = true) Integer topState){
        try {
            iTopicInfoService.topOrUnTopTopic(topicId,topState);
        }catch (Exception e){
            log.error("置頂主題异常|TopicInfoController|updateTopic:topicId={},topState={},error={}",topicId,topState,e );
            return ApiResult.build(ResultCode.HANDLE_FAIL.getCode(), ResultCode.HANDLE_FAIL.getName());
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), null);
    }

}